package com.sdy.dcsb.web.util;

import org.apache.commons.collections4.ListUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Snaky
 * @date 2020/4/21 9:30
 */
public class ListUtil {

    /**
     * 集合数据分页
     * @param list 分页数据
     * @param pageSize 分页大小,默认为10
     * @param currentPage 当前页面，默认为1
     * @return 分页数据
     */
    public static <T> List<T> page(List<T> list, int pageSize, int currentPage){
        if(pageSize <= 0){
            pageSize = 10;
        }
        if(currentPage <= 0){
            currentPage = 1;
        }
        List<List<T>> pagedList = ListUtils.partition(list, pageSize);
        List<T> result;
        if(currentPage > pagedList.size()){
            result = new ArrayList<>();
        }else {
            result = pagedList.get(currentPage - 1);
        }
        return result;
    }

    /**
     * 集合数据分页
     * @param list 分页数据
     * @param pageSize 分页大小,默认为10
     * @param currentPage 当前页面，默认为1
     * @return 分页数据
     */
    public static <T> List<T> pageBySubList(List<T> list, int pageSize, int currentPage) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        if (currentPage <= 0) {
            currentPage = 1;
        }
        int total = list.size();
        int pageCount;
        int m = total % pageSize;
        if (m > 0) {
            pageCount = total / pageSize + 1;
        } else {
            pageCount = total / pageSize;
        }
        List<T> subList;
        if (m == 0) {
            subList = list.subList((currentPage - 1) * pageSize, pageSize * (currentPage));
        } else {
            if (currentPage == pageCount) {
                subList = list.subList((currentPage - 1) * pageSize, total);
            } else {
                subList = list.subList((currentPage - 1) * pageSize, pageSize * (currentPage));
            }
        }
        return subList;
    }
}
